package com.zwcl.glass.tools.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zwcl.common.core.utils.http.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class GaodeMapUtils {

    private static String key = "456357b7d897a276612e552ffe417079";
    /**
     * 阿里云api 根据经纬度获取地址
     *
     * @param lat
     * @return
     */
    public static String getAdd(String location, String lat) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(location).append(",").append(lat);
        String res =HttpUtils.sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
        log.info(res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.getString("regeocode"));
        String add = jsonObject1.get("formatted_address").toString();
        return add;
    }

    /**
     * 阿里云api 根据经纬度获取所在城市
     *
     * @param lat
     * @return
     */
    public static String getCity(String location, String lat) {
        // log 大 lat 小
        // 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + location + "&type=010";
        String res = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream
                    (), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();
            JSONObject jsonObject = JSONObject.parseObject(res);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("addrList"));
            JSONObject j_2 = jsonArray.getJSONObject(0);
            String allAdd = j_2.getString("admName");
            String arr[] = allAdd.split(",");
            res = arr[1];
        } catch (Exception e) {
            log.info("error in wapaction,and e is " + e.getMessage());
        }
        log.info(res);
        return res;
    }

    /**
     * 高德api 根据地址获取经纬度
     *
     * @param name
     * @return
     */
    public static String getLatAndLogByName(String name) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&address=" + name);
        String res = HttpUtils.sendPost("http://restapi.amap.com/v3/geocode/geo", s.toString());
        log.info(res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("geocodes"));
        JSONObject location = (JSONObject) jsonArray.get(0);
        String add = location.get("location").toString();
        return add;
    }

    /**
     * 高德api 根据地址获取经纬度
     *
     * @return
     */
    public static String getAddByAMAP(String location, String lat) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&location=").append(location).append(",").append(lat);
        String res = HttpUtils.sendPost("http://restapi.amap.com/v3/geocode/regeo", s.toString());
        log.info(res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.getString("regeocode"));
        String add = jsonObject1.get("formatted_address").toString();
        return add;
    }


    /**
     * 高德api 坐标转换---转换至高德经纬度
     * @return
     */
    public static String convertLocations(String location, String lat, String type) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(key).append("&locations=").append(location).append(",").append(lat).append("&coordsys=");
        if (type == null) {
            s.append("gps");
        } else {
            s.append(type);
        }
        String res = HttpUtils.sendPost("http://restapi.amap.com/v3/assistant/coordinate/convert", s.toString());
        log.info(res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String add = jsonObject.get("locations").toString();
        return add;
    }

    public static String getAddByName(String name) {
        // log 大 lat 小
        // 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = "http://gc.ditu.aliyun.com/geocoding?a=" + name;
        String res = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line + "\n";
            }
            in.close();
            JSONObject jsonObject = JSONObject.parseObject(res);
            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            System.err.println(jsonObject);
            res = getNearbyAdd(lon, lat);
        } catch (Exception e) {
            log.info("error in wapaction,and e is " + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    public static String getNearbyAdd(String location, String lat) {
        String add = HttpUtils.sendGet("http://ditu.amap.com/service/regeo", "longitude=" + location + "&latitude=" + lat +
                "&type=010");
        log.info(add);
        return add;
    }

    /**
     * 高德api 关键字模糊查询
     *
     * @param keyWord
     * @param city
     * @return
     */
    public static String getKeywordsAddByLbs(String keyWord, String city) {
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&keywords=");
        if (keyWord.contains(" ")) {
            String[] str = keyWord.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (i == 0) {
                    s.append(str[i]);
                } else {
                    s.append("+" + str[i]);
                }
            }
        } else {
            s.append(keyWord);
        }
        s.append("&city=" + city);
        s.append("&offset=10&page=1");
        String around = HttpUtils.sendPost("http://restapi.amap.com/v3/place/text", s.toString());
        log.info(around);
        return around;
    }
    /**
     * 高德api 经纬度/关键字 附近地标建筑及地点查询
     *
     * @param location
     * @param lat
     * @param keyWord
     * @return
     */
    public static String getAroundAddByLbs(String location, String lat, String keyWord) {
        String around = HttpUtils.sendPost("http://restapi.amap.com/v3/place/around",
                "key=" + key + "&location=" + location + "," + lat + "&keywords=" + keyWord +
                        "&radius=2000&offset=10&page=1");
        log.info(around);
        return around;
    }

    //https://yuntuapi.amap.com/datasearch/local?tableid=52b155b6e4b0bc61deeb7629&city=北京市&keywords= &filter=type:写字楼&limit=50&page=1&key=<用户key> //搜索存储在云图数据表中的北京市的写字楼，返回第一页数据
    //restapi.amap.com/v3/place/text?key=您的key&keywords=验光中心&types=&city=广州&children=1&offset=20&page=1&extensions=all
    public static String getKeywordsAddByCity(String keyWord, String city){
        StringBuffer s = new StringBuffer();
        s.append("key=" + key + "&keywords=");
        if (keyWord.contains(" ")) {
            String[] str = keyWord.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (i == 0) {
                    s.append(str[i]);
                } else {
                    s.append("+" + str[i]);
                }
            }
        } else {
            s.append(keyWord);
        }
        s.append("&city=" + city);
        s.append("&offset=10&page=1&extensions=all");
        String url = "https://restapi.amap.com/v3/place/text?"+s.toString();
        String around= HttpClientUtils.makeHttpRequestStringResult(url, HttpGet.METHOD_NAME);
        //String around = HttpUtils.sendPost("https://restapi.amap.com/v3/place/text", s.toString());
        log.info(around);
        return around;
    }
}
